<template>
	<view class="order-container">
		<!-- 状态筛选 -->
		<view class="status-filter">
			<button v-for="status in statusList" :key="status"
				:class="['status-btn', { 'active': selectedStatus === status }]" @tap="selectedStatus = status">
				{{ status }}
			</button>
		</view>

		<!-- 订单列表 -->
		<scroll-view class="order-list" scroll-y>
			<view v-for="order in filteredOrders" :key="order.orderId" class="order-card" :class="{
        'processing': order.status === '制作中',
        'pickup-ready': order.status === '待取餐',
        'completed': order.status === '已完成'
      }">
				<!-- 订单头部 -->
				<view class="order-header">
					<text class="order-id">#{{ order.orderId }}</text>
					<view class="time-info">
						<text class="order-time">{{ formatTime(order.orderTime) }}</text>
						<text v-if="order.status !== '已完成'" class="elapsed">
							{{ statusTimeInfo(order) }}
						</text>
					</view>
				</view>

				<!-- 商品列表 -->
				<view class="goods-list">
					<view v-for="(item, index) in order.items" :key="item.itemId" class="goods-item">
						<text class="name">{{ item.name }}</text>
						<text class="quantity">×{{ item.quantity }}</text>
						<text class="price">￥{{ (Number(item.price) * item.quantity).toFixed(2) }}</text>
					</view>
				</view>

				<!-- 底部操作 -->
				<view class="order-footer">
					<text class="total">总价: ￥{{ Number(order.totalPrice).toFixed(2) }}</text>
					<button class="action-btn" :class="getButtonClass(order.status)" @tap="handleOrderAction(order)"
						:disabled="order.status === '已完成'">
						{{ getButtonText(order.status) }}
					</button>
				</view>
			</view>

			<view v-if="filteredOrders.length === 0" class="empty-state">
				<!-- <image src="/static/empty-order.png" class="empty-image" /> -->
				<text class="empty-text">暂无相关订单</text>
			</view>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted,
		onUnmounted
	} from 'vue'
	import {
		adminUpdateOrderState,
		adminQueryOrderList
	} from '../../request/api.js'
	import {
		useUserStore
	} from '../../stores/user.js'

	const statusList = ['全部', '待制作', '待取餐', '已完成']
	const selectedStatus = ref('全部')
	const socket = ref(null)
	const orders = ref([])
	const restaurantId = useUserStore().student_id // 根据实际情况修改

	// 加载订单数据
	const loadOrders = async () => {
		const res = await adminQueryOrderList(restaurantId)
		orders.value = res.orders.map(order => ({
			...order,
			elapsedMinutes: calcElapsedMinutes(order.orderTime)
		}))
	}

	// 计算经过时间
	const calcElapsedMinutes = (isoString) => {
		return Math.floor((Date.now() - new Date(isoString)) / 60000)
	}

	// 过滤和排序订单
	const filteredOrders = computed(() => {
		return orders.value
			.filter(order => {
				switch (selectedStatus.value) {
					case '全部':
						return true
					case '待制作':
						return order.status === '制作中'
					case '待取餐':
						return order.status === '待取餐'
					case '已完成':
						return order.status === '已完成'
					default:
						return true
				}
			})
			.sort((a, b) => new Date(b.orderTime).getTime() - new Date(a.orderTime).getTime())
	})

	// 时间格式化
	const formatTime = (isoString) => {
		const date = new Date(isoString)
		return `${date.getFullYear().toString()}-${(date.getMonth()+1).toString()}-${date.getDate().toString()}-${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
	}

	// 订单操作处理
	const handleOrderAction = async (order) => {
		try {
			let newStatus
			if (order.status === '制作中') {
				newStatus = '待取餐'
			} else if (order.status === '待取餐') {
				newStatus = '已完成'
			} else {
				return
			}

			await adminUpdateOrderState(order.orderId, newStatus)
			order.status = newStatus
			order.elapsedMinutes = calcElapsedMinutes(order.orderTime)

			uni.showToast({
				title: '操作成功',
				icon: 'success'
			})
		} catch (error) {
			uni.showToast({
				title: '操作失败',
				icon: 'none'
			})
		}
	}

	// 获取按钮文字
	const getButtonText = (status) => {
		const statusMap = {
			'制作中': '标记出餐',
			'待取餐': '确认取餐',
			'已完成': '已完成'
		}
		return statusMap[status] || '未知状态'
	}

	// 获取按钮样式类
	const getButtonClass = (status) => {
		return {
			processing: status === '制作中',
			'pickup-ready': status === '待取餐',
			disabled: status === '已完成'
		}
	}

	// 时间状态信息
	const statusTimeInfo = (order) => {
		if (order.status === '制作中') {
			return `已等待 ${order.elapsedMinutes} 分钟`
		}
		if (order.status === '待取餐') {
			return `已就绪 ${order.elapsedMinutes} 分钟`
		}
		return ''
	}

	// WebSocket 初始化
	onMounted(() => {
		loadOrders()
		initWebSocket()
	})

	onUnmounted(() => {
		if (socket.value) socket.value.close()
	})

	const initWebSocket = () => {
		socket.value = uni.connectSocket({
			url: `ws://175.178.118.46:3000?restaurant_id=${restaurantId}`,
			success: () => console.log('WebSocket 连接成功'),
			fail: (err) => console.error('连接失败:', err)
		})

		socket.value.onMessage((res) => {
			const newOrder = JSON.parse(res.data)
			if (newOrder.restaurantId === restaurantId) {
				orders.value = [newOrder, ...orders.value]
			}
		})
	}
</script>

<style scoped>
	.order-container {
		padding: 20rpx;
		background-color: #f8f9fa;
		height: 100vh;
		box-sizing: border-box;
	}

	.status-filter {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.status-btn {
		flex: 1;
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 35rpx;
		background-color: #e4e7ed;
		color: #606266;
		font-size: 28rpx;
		border: none;
		transition: all 0.3s;
	}

	.status-btn.active {
		background-color: #409eff;
		color: white;
	}

	.order-list {
		height: calc(100vh - 140rpx);
	}

	.order-card {
		background: white;
		border-radius: 16rpx;
		margin-bottom: 24rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
		position: relative;
	}

	.order-card.processing {
		border-left: 8rpx solid #409eff;
	}

	.order-card.pickup-ready {
		border-left: 8rpx solid #e6a23c;
	}

	.order-card.completed {
		opacity: 0.7;
		background-color: #f8f9fa;
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.order-id {
		font-size: 32rpx;
		color: #303133;
		font-weight: 500;
	}

	.time-info {
		text-align: right;
	}

	.order-time {
		display: block;
		font-size: 28rpx;
		color: #909399;
	}

	.elapsed {
		font-size: 24rpx;
		color: #f56c6c;
	}

	.goods-list {
		margin-bottom: 24rpx;
	}

	.goods-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 16rpx 0;
		border-bottom: 1rpx solid #ebeef5;
	}

	.goods-item:last-child {
		border-bottom: none;
	}

	.name {
		flex: 1;
		font-size: 28rpx;
		color: #606266;
	}

	.quantity {
		margin: 0 30rpx;
		font-size: 26rpx;
		color: #909399;
	}

	.price {
		font-size: 28rpx;
		color: #303133;
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 24rpx;
		border-top: 1rpx solid #ebeef5;
	}

	.total {
		font-size: 30rpx;
		color: #303133;
		font-weight: 500;
	}

	.action-btn {
		height: 64rpx;
		line-height: 64rpx;
		padding: 0 40rpx;
		border-radius: 32rpx;
		font-size: 28rpx;
		transition: all 0.3s;
	}

	.action-btn.processing {
		background-color: #409eff;
		color: white;
	}

	.action-btn.pickup-ready {
		background-color: #e6a23c;
		color: white;
	}

	.action-btn.disabled {
		background-color: #c0c4cc;
		color: white;
	}

	.empty-state {
		padding: 100rpx 0;
		text-align: center;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		opacity: 0.6;
		margin-bottom: 24rpx;
	}

	.empty-text {
		color: #999;
		font-size: 28rpx;
	}
</style>